package me.zhengjie.modules.system.service.impl;

import me.zhengjie.modules.system.domain.Area;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.AreaRepository;
import me.zhengjie.modules.system.service.AreaService;
import me.zhengjie.modules.system.service.dto.AreaDTO;
import me.zhengjie.modules.system.service.mapper.AreaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-06
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaRepository areaRepository;

    @Autowired
    private AreaMapper areaMapper;

    @Override
    public AreaDTO findById(Long id) {
        Optional<Area> area = areaRepository.findById(id);
        ValidationUtil.isNull(area,"Area","id",id);
        return areaMapper.toDto(area.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaDTO create(Area resources) {
        return areaMapper.toDto(areaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Area resources) {
        Optional<Area> optionalArea = areaRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalArea,"Area","id",resources.getId());

        Area area = optionalArea.get();
        // 此处需自己修改
        resources.setId(area.getId());
        areaRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        areaRepository.deleteById(id);
    }
}